// src/store/authStore.ts
import { refreshToken as refreshTokenApi } from '@/api/login/userLogin';
import { debounce } from 'lodash';
import { useRouter } from 'vue-router';

const router = useRouter()
// 定期刷新token，保证验证信息不过期, 上次刷新时间存储在localStorage中
const REFRESH_INTERVAL = 1000 * 60 * 10 // 10分钟
const LAST_REFRESH_KEY = 'last_token_refresh_time'

// 添加防抖
export const refreshTokenMethod = debounce(async () => {
  const currentTime = new Date().getTime()
  try {
    const lastRefreshTime = Number(localStorage.getItem(LAST_REFRESH_KEY)) || 0
    // note: 无需获取Cookie或者响应后设置Cookie，因为Cookie可以直接设置在浏览器
    if (currentTime - lastRefreshTime > REFRESH_INTERVAL)
      await refreshTokenApi()
  }
  catch (error) {
    console.error('刷新token失败:', error)
    // 跳转到登录页面
    router.push('/login')
  }
  finally {
    // 只要请求不管成功与否，都更新刷新时间
    localStorage.setItem(LAST_REFRESH_KEY, currentTime.toString())
  }
}, 1000)
